package com.diaohw.platform.framework.rabbit;

import com.diaohw.platform.common.obj.thread.RequestThread;
import com.diaohw.platform.common.util.JsonUtil;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

import static com.diaohw.platform.common.constant.RequestConstant.*;

@Service
public class RabbitMQUService {


    @Resource
    RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     *
     * @param exchange   交换机地址
     * @param routingKey 路由
     * @param data       数据
     */
    public void sendMessage(String exchange, String routingKey, Object data) {
        Message message = getMessage(data);
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }

    /**
     * 发送消息
     *
     * @param exchange 交换机地址
     * @param data     数据
     */
    public void sendMessage(String exchange, Object data) {
        Message message = getMessage(data);

        rabbitTemplate.convertAndSend(exchange, message);
    }

    /**
     * 通过协议头获取当前用户信息
     *
     * @param message
     */
    public void header(Message message) {
        MessageProperties properties = message.getMessageProperties();

        String requestId = properties.getHeader(REQUEST_ID);

        String linkId = properties.getHeader(LINK_ID);

        String authorization = properties.getHeader(AUTHORIZATION);


    }


    /**
     * 组装消息体
     */
    private Message getMessage(Object data) {

        MessageProperties properties = new MessageProperties();
        properties.setHeader(REQUEST_ID, RequestThread.getThreadRequestId());
        properties.setHeader(LINK_ID, RequestThread.getThreadLinkId());
        properties.setHeader(AUTHORIZATION, RequestThread.getThreadAuthorization());

        return new Message(JsonUtil.toJsonString(data).getBytes(StandardCharsets.UTF_8), properties);
    }


}
